<?php

namespace Biblibase\SiteBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

use Biblibase\SiteBundle\Entity\Livre;

use Biblibase\SiteBundle\Form\UpdateLivreType;

class ConsultationController extends Controller
{
	private function checkCascade($livre)
	{
		$livre->getEditeur()->getNom();
		$em = $this->getDoctrine()->getManager();
		$repAuteur = $em->getRepository('BiblibaseSiteBundle:Auteur');
		$repEditeur = $em->getRepository('BiblibaseSiteBundle:Editeur');
		$repCollection	= $em->getRepository('BiblibaseSiteBundle:Collection');
		$repLivre = $em->getRepository('BiblibaseSiteBundle:Livre');
		
		foreach($livre->getAuteur() as $auteur)
		{
			$nbAuteur = $repLivre->getCountAuteur($auteur);			
			foreach($nbAuteur as $a)
			{
				if($a == 1)
				{
					$em->remove($auteur);			
				}
			}		
		}
	
		$nbEditeur = $repLivre->getCountEditeur($livre->getEditeur());
		$nbCollection = $repLivre->getCountCollection($livre->getCollection());
		
		foreach($nbEditeur as $a)
		{
			if($a == 1)
			{
				$em->remove($livre->getEditeur());			
			}
		}
		
		foreach($nbCollection as $a)
		{
			if($a == 1)
			{
				$em->remove($livre->getCollection());			
			}
		}
	}
	
	private function checkExist($livre)
	{
		$em = $this->getDoctrine()->getManager();
    		 		
    	$auteurRep = $em->getRepository('BiblibaseSiteBundle:Auteur');
    	$editeurRep = $em->getRepository('BiblibaseSiteBundle:Editeur');
    	$collectionRep = $em->getRepository('BiblibaseSiteBundle:Collection');
    		 		
    	$exist = $collectionRep->findOneBy(array('nom' => $livre->getCollection()->getNom()));
    	if($exist)
    	{
		  $livre->setCollection($exist);  		 		
    	}
    	 		
    	foreach($livre->getAuteur() as $aut)
    	{
    		$exist = $auteurRep->findOneBy(array('nom' => $aut->getNom()));
    		if($exist)
    		{
    			echo $livre->getAuteur()[0]->getNom();
    			$livre->removeAuteur($aut);
			   $livre->addAuteur($exist); 		 		
    		}
    	}
    		 		
    	$exist = $editeurRep->findOneBy(array('nom' => $livre->getEditeur()->getNom()));
    	if($exist)
    	{
		  $livre->setEditeur($exist);  		 		
    	}
	}

	public function consultationAction()
    {
        return $this->render('BiblibaseSiteBundle:Site:consultation.html.twig');
    }

	public function getNavigationAction($name)
	{
		if(!isset($name))
		{
			$return=array("error"=>"true", "message"=>"recherche impossible");
		 	$return=json_encode($return);
		 	return new Response($return,200,array('Content-Type'=>'application/json'));
		}
		else 
		{
			$em = $this->getDoctrine()->getManager();
			
			if($name == "auteur" || $name == "collection" || $name == "editeur" || $name == "theme" || $name == "classement")		
			{
				$rep = $em->getRepository('BiblibaseSiteBundle:'.ucfirst($name));
				$result = $rep->getOrderByNom();
				$return = array();
				$return["result"] = array();
				for($i = 0; $i < count($result); $i++)
				{
					$return["result"][$i] = $result[$i]->getNom();					
				}
				
		 		$return=json_encode($return);
		 		return new Response($return,200,array('Content-Type'=>'application/json'));
			}
			else if($name == "annee")
			{
				$rep = $em->getRepository('BiblibaseSiteBundle:Livre');
				$result = $rep->getByAnnee();
				$return = array();
				$return["result"] = array();
				for($i = 0; $i < count($result); $i++)
				{
					if($result[$i]->getAnnee() != null)
						$return["result"][$i] = $result[$i]->getAnnee();
				}
				
		 		$return=json_encode($return);
		 		return new Response($return,200,array('Content-Type'=>'application/json'));
				
			}
			else 
			{
				$rep = $em->getRepository('BiblibaseSiteBundle:Livre');
				if($name == "titre")
						$result = $rep->getByTitre();
					else if($name == "isbn")	
						$result = $rep->getByIsbn();
				
				$return = array();
				$return["result"] = array();
				for($i = 0; $i < count($result); $i++)
				{
					if($name == "titre")
						$return["result"][$i] = $result[$i]->getTitre();
					else if($name == "isbn")	
						$return["result"][$i] = $result[$i]->getIsbn();	
				}
				
		 		$return=json_encode($return);
		 		return new Response($return,200,array('Content-Type'=>'application/json'));
			}	
		}
	}
	
	public function getAction($name, $value)
	{
		if(!isset($name) || !isset($value))
		{
			$return=array("error"=>"true", "message"=>"recherche impossible");
		 	$return=json_encode($return);
		 	return new Response($return,200,array('Content-Type'=>'application/json'));
		}
		else 
		{
			$em = $this->getDoctrine()->getManager();
			$rep = $em->getRepository('BiblibaseSiteBundle:Livre');
			
			if($name == "auteur" || $name == "collection" || $name == "editeur" || $name == "theme" || $name == "classement")		
			{
				$rep2 = $em->getRepository('BiblibaseSiteBundle:'.ucfirst($name));
				$result = $rep->getLivreCompletBy($name, $rep2->findByNom($value));
			}
			else 
			{
				$result = $rep->getLivreCompletBy($name, $value);
			}
		
			$return = array();
			$return["result"] = array();
			for($i = 0; $i < count($result); $i++)
			{
				$return["result"][$i] = array("titre" => $result[$i]->getTitre(),
														"auteur" => $result[$i]->getAuteur()[0]->getNom(),
														"collection" => $result[$i]->getCollection()->getNom(),
														"editeur" => $result[$i]->getEditeur()->getNom(),
														"theme" => -1,
														"isbn" => $result[$i]->getIsbn(),
														"classement" => -1,
														"annee" => $result[$i]->getAnnee(),
														);
				if($result[$i]->getThemes()[0])
					$return["result"][$i]["theme"] = $result[$i]->getThemes()[0]->getNom();
				if($result[$i]->getClassement())
					$return["result"][$i]["classement"] = $result[$i]->getClassement()->getNom();
			}
				
		 	$return=json_encode($return);
		 	return new Response($return,200,array('Content-Type'=>'application/json'));	
		}		
	}
	
	public function updateLivreAction($isbn)
	{
		$em = $this->getDoctrine()->getManager();
		$rep = $em->getRepository('BiblibaseSiteBundle:Livre');
		$livre = $rep->findOneByIsbn($isbn);
  		$form = $this->createForm(new UpdateLivreType, $livre);
 
  		 $request = $this->get('request');
  		 if ($request->getMethod() == 'POST') {
    			$form->bind($request);
 
    		 	if ($form->isValid()) {
    		 		
      			$livre2 = new Livre();
					$livre2->copier($livre);
					
					$em->refresh($livre);
					foreach($livre->getAuteur() as $a)
						$em->refresh($a);
						
					$em->refresh($livre->getEditeur());
					$em->refresh($livre->getCollection());
					
					$this->deleteLivreAction($livre->getIsbn(), false);
					
      			$this->checkExist($livre2);
      			
      			$em->persist($livre2);
      			$em->flush();
      			
 
      			$return=array("error"=>"false", "message"=>"Livre modifié");
		 			$return=json_encode($return);
		 			return new Response($return,200,array('Content-Type'=>'application/json'));
    			}
  		  }
 
  		return $this->render('::formUpdate.html.twig', array(
    		'form' => $form->createView(),
    		'route' => $this->generateUrl('biblibase_site_updateLivre', array('isbn' => $isbn)),
    		'sup' => $this->generateUrl('biblibase_site_deleteLivre', array('isbn' => $isbn))
  		));
	}
	
	public function deleteLivreAction($isbn, $image = true)
	{
		$em = $this->getDoctrine()->getManager();
		$rep = $em->getRepository('BiblibaseSiteBundle:Livre');
		$livre = $rep->findOneByIsbn($isbn);
		$livre2 = new Livre();
		$livre2->copier($livre);
		
		$em->remove($livre);
		$this->checkCascade($livre);
		if($image)
		{
			if($livre->getImage() != null)
				$em->remove($livre->getImage());
		}
		
		$em->flush();
		
		$return=array("error"=>"false", "message"=>"Livre supprimé");
		 			$return=json_encode($return);
		 			return new Response($return,200,array('Content-Type'=>'application/json'));
	}

	public function getImageAction($isbn)
	{
		$em = $this->getDoctrine()->getManager();
		$rep = $em->getRepository('BiblibaseSiteBundle:Livre');
		$livre = $rep->findOneByIsbn($isbn);
		
		if($livre->getImage())
		{
			$return=array("img"=>$this->container->get('templating.helper.assets')->getUrl('uploads/img').'/'.$livre->getImage()->getId().'.'.$livre->getImage()->getSrc());
		}
		else 
		{
			$return=array("img"=>$this->container->get('templating.helper.assets')->getUrl('img').'/default.png');
		}
		$return=json_encode($return);
		return new Response($return,200,array('Content-Type'=>'application/json'));
	}
}